package com.zj.juc.study.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName AtomicTypeReferenceUpdaterDemo
 * @Description 对象属性原子修改类demo
 * @createTime 2025年01月03日 20:53
 */
public class AtomicTypeReferenceUpdaterDemo {

    /**
     * 要求：多线程并发调用一个类的初始化方法，如果未被初始化过将执行初始化工作
     * 要求只能被初始化一次，只有一个线程操作成功
     *
     */
    public static Integer SIZE = 50;


    public static void main(String[] args) {
        AtomicReferenceFieldUpdater<MyVar,Boolean> referenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(MyVar.class,Boolean.class,"isInit");
        MyVar myVar = new MyVar();

        CountDownLatch countDownLatch = new CountDownLatch(SIZE);

        for (int i = 0; i < SIZE; i++) {
            try {
                new Thread(()->{
                    for (int j = 0; j < 100; j++) {
                        if (referenceFieldUpdater.compareAndSet(myVar,false,true)){
                            System.out.println(Thread.currentThread().getName()+"update success");
                        }else {
                            System.out.println(Thread.currentThread().getName()+" can not update");
                        }
                    }
                },String.valueOf(i)).start();
            } finally {
                countDownLatch.countDown();
            }
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}


class MyVar{
    public volatile Boolean isInit = false;
}
